<?php

/**
 * 用户需求
 */

namespace app\api\model;


use app\common\lib\RespCode;
use app\crontab\controller\HelpDemandAutoPush;
use custom\Err;
use custom\Redis;
use custom\Token;
use PDOStatement;
use think\Collection;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class AgentDemand extends Model
{

    const TYPE1 = 1; //不限
    const TYPE2 = 2;//只看小区
    const TYPE3 = 3;//只看商圈

    /**
     * ver 1.0.1
     * 添加/编辑需求
     * @param $params
     * @return int|string
     * @throws Exception
     * @throws PDOException
     */
    public static function edit($params)
    {
        if ($params['type'] != self::TYPE2 && $params['type'] != self::TYPE3) {
            $params['type_id'] = 0;
        } else {
            if (empty($params['type_id'])) {
                Err::add('请选择小区或者商圈', RespCode::PARAMS_ERR);
                return false;
            }
        }
        $data = [
            'agent_id' => $params['agent_id'],
            'city_code' => intval($params['city_code']),
            'area_code' => trim($params['area_code']),
            'price_section' => trim($params['p_key']),
            'area_section' => trim($params['a_key']),
            'door_section' => trim($params['h_key']),
            'type' => intval($params['type']),
            'type_id' => intval($params['type_id']),
            'itime' => time(),
        ];
        if (empty($params['id'])) {
            $count = db("agent_demand")->where('agent_id', $params['agent_id'])->count();
            if ($count >= 3) {
                Err::add('最多保存3条需求', RespCode::QUERY_ERR);
                return false;
            } else {
                $add_de = db('agent_demand')->insert($data);
                if ($add_de) {
                    return true;
                } else {
                    Err::add('保存失败', RespCode::QUERY_ERR);
                    return false;
                }
            }
        } else {
            $up_de = db('agent_demand')->where('id', $params['id'])->update($data);
            if ($up_de === false) {
                Err::add('保存失败', RespCode::QUERY_ERR);
                return false;
            } else {
                return true;
            }

        }
    }

    /**
     * 编辑 智能选房
     * @param $params
     * @return bool
     */
    public static function editUnlimited($params)
    {
        if ($params['type'] != self::TYPE2 && $params['type'] != self::TYPE3) {
            $params['type_id'] = 0;
        } else {
            if (empty($params['type_id'])) {
                Err::add('请选择小区或者商圈', RespCode::PARAMS_ERR);
                return false;
            }
        }
        $data = [
            'agent_id' => $params['agent_id'],
            'city_code' => intval($params['city_code']),
            'area_code' => trim($params['area_code']),
            'price_section' => trim($params['p_key']),
            'area_section' => trim($params['a_key']),
            'door_section' => trim($params['h_key']),
            'type' => intval($params['type']),
            'type_id' => intval($params['type_id']),
            'itime' => time(),
        ];
        //不限区域判断
        if ($data['area_code']==$data['city_code'].'_all'){
            $data['area_code']='';//不限区域，存入空
        }else{
            $codes=explode(',',$params['area_code']);
            if (count($codes)>5){
                Err::add('区域选择不能超过5个',RespCode::PARAMS_ERR);
                return false;
            }
        }
        //选择商圈或小区
        if ($data['type_id']){
            if ($params['type'] == self::TYPE2){
                //小区
                $area_code=self::getVillageCity($data['type_id']);
            }
            if ($params['type'] == self::TYPE3){
                //商圈
                $area_code=self::getBusinessCity($data['type_id']);
            }
            $data['area_code']=$area_code;
        }
        if (empty($params['id'])) {
            $count = db("agent_demand")->where('agent_id', $params['agent_id'])->count();
            if ($count >= 3) {
                Err::add('最多保存3条需求', RespCode::QUERY_ERR);
                return false;
            } else {
                $add_de = db('agent_demand')->insert($data);
                if ($add_de) {
                    return true;
                } else {
                    Err::add('保存失败', RespCode::QUERY_ERR);
                    return false;
                }
            }
        } else {
            $up_de = db('agent_demand')->where('id', $params['id'])->update($data);
            if ($up_de === false) {
                Err::add('保存失败', RespCode::QUERY_ERR);
                return false;
            } else {
                return true;
            }

        }
    }

    /**
     * ver 1.0.0
     *  * 展示需求小区/房源
     * @param $params
     * @return array
     */
    public static function show($params)
    {
        $data = db("agent_demand")
            ->alias('ud')
            ->leftJoin('region r', 'r.city_code=ud.city_code')
            ->leftJoin('region r1', 'r1.city_code=ud.area_code')
            ->where('ud.agent_id', $params['agent_id'])
            ->field('r.name as city_name,ud.id,ud.type_id,ud.type,r1.name as area_name,ud.price_section,ud.city_code,ud.area_code,ud.area_section,ud.door_section')
            ->select();
//       print_r($data);exit;
        if (empty($data)) {
            return [];
        } else {
            foreach ($data as &$v) {
                if ($v['type'] == self::TYPE1) {
                    $v['list_typename'] = '不限';
                    $v['info_business_or_community'] = '';
                }
                if ($v['type'] == self::TYPE2) {
                    $v_name = HouseVillage::get_Name($v['type_id']);
                    $v['list_typename'] = "只看'" . $v_name . "'小区";
                    $v['info_business_or_community'] = $v_name;
                }
                if ($v['type'] == self::TYPE3) {
                    $a_name = BusinessArea::get_Name($v['type_id']);
                    $v['list_typename'] = "只看'" . $a_name . "'商圈";
                    $v['info_business_or_community'] = $a_name;
                }
                //列表展示市-区
                $v['list_title'] = $v['city_name'] . '-' . $v['area_name'];
                $v['info_city_name'] = $v['city_name'];
                $v['info_area_name'] = $v['area_name'];
                unset($v['city_name']);
                unset($v['area_name']);
                $price_section = explode('-', $v['price_section']);
                $v['list_price_section'] = IntervalConfig::getConfig_name($price_section[0], $price_section[1], 1);
                $v['info_city_code'] = $v['city_code'];
                $v['info_area_code'] = $v['area_code'];
                $v['info_price_section'] = $v['price_section'];
                $v['info_area_section'] = $v['area_section'];
                $v['info_type'] = $v['type'];
                $v['info_business_or_community_id'] = $v['type_id'];
                unset($v['type']);
                unset($v['city_code']);
                unset($v['area_code']);
                $ps = explode('-', $v['price_section']);
                $v['info_price_section_name'] = IntervalConfig::getConfig_name($ps[0], $ps[1], 1);
                $as = explode('-', $v['area_section']);
                $v['info_area_section_name'] = IntervalConfig::getConfig_name($as[0], $as[1], 2);
                unset($v['price_section']);
                unset($v['area_section']);
                unset($v['type_id']);
                $v['info_door_section'] = $v['door_section'];
                if ($v['door_section']) {
                    $hs = explode('-', $v['door_section']);
                    $v['info_door_section_name'] = IntervalConfig::getConfig_name($hs[0], $hs[1], 6);
                } else {
                    $v['info_door_section_name'] = '';
                }
                unset($v['door_section']);
            }
            return array_values($data);
        }
    }

    /**
     * 展示需求小区/房源
     * @param $params
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function newShow($params)
    {
        $data = db("agent_demand")
            ->field('r.name as city_name,ud.id,ud.type_id,ud.type,ud.price_section,ud.city_code,ud.area_code,ud.area_section,ud.door_section')
            ->alias('ud')
            ->leftJoin('region r', 'r.city_code=ud.city_code')
            ->where('ud.agent_id', $params['agent_id'])
            ->select();
        if (empty($data)) {
            return [];
        } else {
            foreach ($data as &$v) {
                if ($v['type'] == self::TYPE1) {
                    $v['list_typename'] = '不限';
                    $v['info_business_or_community'] = '';
                }
                if ($v['type'] == self::TYPE2) {
                    $v_name = HouseVillage::get_Name($v['type_id']);
                    $v['list_typename'] = "只看'" . $v_name . "'小区";
                    $v['info_business_or_community'] = $v_name;
                }
                if ($v['type'] == self::TYPE3) {
                    $a_name = BusinessArea::get_Name($v['type_id']);
                    $v['list_typename'] = "只看'" . $a_name . "'商圈";
                    $v['info_business_or_community'] = $a_name;
                }
                $area_name = self::getArea($v['area_code'],$v['city_code']);//区域集合
                //列表展示市-区
                $v['list_title'] = self:: dealCityArea($area_name, $v['city_name']);
                $v['info_city_info'] = array('city_code' => $v['city_code'], 'name' => $v['city_name']);
                $v['info_area_info'] = $area_name;

                $v['info_type'] = $v['type'];
                $v['info_business_or_community_id'] = $v['type_id'];
                unset($v['type']);
                unset($v['city_name']);
                unset($v['city_code']);
                unset($v['area_code']);
                $v['info_price_section'] = $v['price_section'] ? explode(',', $v['price_section']) : [];
                $v['info_price_section_name'] = self::managerDemand($v['price_section'], 1);
                $v['info_area_section'] = $v['area_section'] ? explode(',', $v['area_section']) : [];
                $v['info_area_section_name'] = self::managerDemand($v['area_section'], 2);
                unset($v['price_section']);
                unset($v['area_section']);
                unset($v['type_id']);
                $v['info_door_section'] = $v['door_section'] ? explode(',', $v['door_section']) : [];
                $v['info_door_section_name'] = self::managerDemand($v['door_section'], 6);
                unset($v['door_section']);
            }
            return array_values($data);
        }
    }

    /**
     * 删除需求
     * @param $params
     * @return int
     * @throws Exception
     * @throws PDOException
     */
    public static function del($params)
    {
        return Db::name("agent_demand")->where('agent_id', $params['agent_id'])->delete($params['id']);
    }

    /**
     * 获取单个需求
     * @param $id
     * @return array|PDOStatement|string|Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getOne($id)
    {
        return Db::name("agent_demand")->where('id', $id)->find();
    }

    /**
     * 我的需求数量
     * @param $uid
     * @return array|PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getMycount($uid)
    {
        return Db::name("agent_demand")->where('agent_id', $uid)->select();
    }

    public static function getArea($area_code='',$city_code='')
    {
        $re=[];
        if (empty($area_code)){
            //不限制区域
            $re[]=['name'=>'不限','city_code'=>$city_code.'_all'];
        }else{
            $re = db('region')->field('city_code,name')->where("city_code in ($area_code) and rank=3")->select();
        }
        return $re;

    }

    public static function dealCityArea($area, $city)
    {
        if (!$area) return $arr = '';
        $area_name = implode('-', array_column($area, 'name'));
        $arr = $city . '-' . $area_name;
        return $arr;
    }

    /**
     * 需求格式处理
     * @param $data
     * @param $type
     * @return array
     */
    public static function managerDemand($data, $type)
    {
        if (!$data) {
            return [];
        } else {
            $all = explode(',', $data);
            foreach ($all as $key => $value) {
                $ps = explode('-', $value);
                $demand[] = $value ? IntervalConfig::getConfig_name($ps[0], $ps[1], $type) : '';//价格区间
            }
            return $demand;
        }
    }

    public function addHelpUserDemand($params)
    {
        $Agent = new Agent();
        //检测当前经纪人与用户是否关联（无关联不能帮填）
        $is_agent_user = $Agent->getAgentUser($params['agent_id'], $params['user_id']);
        if (!$is_agent_user) {
            Err::add('数据不存在', RespCode::DATA_ERR);
            return false;
        }
        if ($params['type'] != self::TYPE2 && $params['type'] != self::TYPE3) {
            $params['type_id'] = 0;
        } else {
            if (empty($params['type_id'])) {
                Err::add('请选择小区或者商圈', RespCode::PARAMS_ERR);
                return false;
            }
        }
        $data = [
            'user_id' => $params['user_id'],
            'agent_id' => $params['agent_id'],
            'city_code' => intval($params['city_code']),
            'area_code' => trim($params['area_code']),
            'price_section' => trim($params['p_key']),
            'area_section' => trim($params['a_key']),
            'door_section' => trim($params['h_key']),
            'type' => intval($params['type']),
            'type_id' => intval($params['type_id']),
            'itime' => time(),
            'utime' => time(),
            'self_write' => 0
        ];

        $user_demand = db('agent_user_demand')->where("agent_id={$params['agent_id']} and user_id={$params['user_id']} and self_write=0")->find();
        Db::startTrans();
        if ($user_demand) {
            //修改
            unset($data['itime']);
            $up_demand = db('agent_user_demand')->where("id={$user_demand['id']}")->update($data);
            if ($up_demand===false) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }
        } else {
            //新增
            $add_demand = db('agent_user_demand')->insert($data);
            if (!$add_demand) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }
            //成为专属客户
            $up_status = $this->addExclusive($params['agent_id'], $params['user_id']);
            if (!$up_status) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }

        }

        $agent_user_id = db('company_agent_user')->where("agent_id={$params['agent_id']} and user_id={$params['user_id']}")->value('id');
        $log=db('agent_user_interaction_log')
            ->where("agent_user_id={$agent_user_id} and type=12")
            ->find();
        if (!$log){
            $res_add = $this->addInterLog($agent_user_id);
            if (!$res_add) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }
        }else{
            $up_log=db('agent_user_interaction_log')
                ->where("id={$log['id']}")
                ->update(['itime'=>time(),'num'=>Db::raw('num+1')]);
            if ($up_log===false) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }
        }


        $up_num=db('company_agent_user')->where("agent_id={$params['agent_id']} and user_id={$params['user_id']}")->update(['last_time'=>time(),'num'=>Db::raw('num+1')]);
        if (!$up_num) {
            Db::rollback();
            Err::add('保存失败', RespCode::PARAMS_ERR);
            return false;
        }

        Db::commit();
        return true;

    }

    /**
     * 帮填需求 （区域新增 不限选项）
     * @param $params
     * @return bool
     */
    public function addHelpUserDemandUnlimited($params)
    {
        $Agent = new Agent();
        //检测当前经纪人与用户是否关联（无关联不能帮填）
        $is_agent_user = $Agent->getAgentUser($params['agent_id'], $params['user_id']);
        if (!$is_agent_user) {
            Err::add('数据不存在', RespCode::DATA_ERR);
            return false;
        }
        if ($params['type'] != self::TYPE2 && $params['type'] != self::TYPE3) {
            $params['type_id'] = 0;
        } else {
            if (empty($params['type_id'])) {
                Err::add('请选择小区或者商圈', RespCode::PARAMS_ERR);
                return false;
            }
        }
        $data = [
            'user_id' => $params['user_id'],
            'agent_id' => $params['agent_id'],
            'city_code' => intval($params['city_code']),
            'area_code' => trim($params['area_code']),
            'price_section' => trim($params['p_key']),
            'area_section' => trim($params['a_key']),
            'door_section' => trim($params['h_key']),
            'type' => intval($params['type']),
            'type_id' => intval($params['type_id']),
            'itime' => time(),
            'utime' => time(),
            'self_write' => 0
        ];
        //不限区域判断
        if ($data['area_code']==$data['city_code'].'_all'){
            $data['area_code']='';//不限区域，存入空
        }
        //选择商圈或小区
        if ($data['type_id']&&$params['type']){
            if ($params['type'] == self::TYPE2){
                //小区
                $area_code=self::getVillageCity($data['type_id']);
            }
            if ($params['type'] == self::TYPE3){
                //商圈
                $area_code=self::getBusinessCity($data['type_id']);
            }
            $data['area_code']=$area_code;
        }
        $user_demand = db('agent_user_demand')->where("agent_id={$params['agent_id']} and user_id={$params['user_id']} and self_write=0")->find();
        Db::startTrans();
        if ($user_demand) {
            //修改
            unset($data['itime']);
            $up_demand = db('agent_user_demand')->where("id={$user_demand['id']}")->update($data);
            if ($up_demand===false) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }
        } else {
            //新增
            $add_demand = db('agent_user_demand')->insert($data);
            if (!$add_demand) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }
            //成为专属客户
            $up_status = $this->addExclusive($params['agent_id'], $params['user_id']);
            if (!$up_status) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }

        }

        $agent_user_id = db('company_agent_user')->where("agent_id={$params['agent_id']} and user_id={$params['user_id']}")->value('id');
        $log=db('agent_user_interaction_log')
            ->where("agent_user_id={$agent_user_id} and type=12")
            ->find();
        if (!$log){
            $res_add = $this->addInterLog($agent_user_id);
            if (!$res_add) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }
        }else{
            $up_log=db('agent_user_interaction_log')
                ->where("id={$log['id']}")
                ->update(['itime'=>time(),'num'=>Db::raw('num+1')]);
            if ($up_log===false) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }
        }


        $up_num=db('company_agent_user')->where("agent_id={$params['agent_id']} and user_id={$params['user_id']}")->update(['last_time'=>time(),'num'=>Db::raw('num+1')]);
        if (!$up_num) {
            Db::rollback();
            Err::add('保存失败', RespCode::PARAMS_ERR);
            return false;
        }

        Db::commit();
        $HelpDemand= new HelpDemandAutoPush();
        if (!$user_demand){
            //新增
            $HelpDemand->editDemand($params['user_id'],$params['agent_id']);//编辑定制选房 发送消息
        }else{
            $is_up=false;
            $is_up=$this->checkDataUp($user_demand,$data);
            if ($is_up){
                $HelpDemand->editDemand($params['user_id'],$params['agent_id']);//编辑定制选房 发送消息
            }

        }
        return true;

    }
    /**
     * 更新成为专属客户
     * @param int $agent_id
     * @param int $user_id
     * @return bool
     */
    public function addExclusive($agent_id = 0, $user_id = 0)
    {
        Db::startTrans();
        $add_exc['status'] = 2;
        $add_exc['is_demand'] = 1;
        $itime_exclusive = time();//成为专属客户时间戳
        $daytime_exclusive = strtotime(date('Y-m-d', time()));//成为专属客户年月日的时间戳
        $add_exc['itime_exclusive'] = $itime_exclusive;
        $add_exc['daytime_exclusive'] = $daytime_exclusive;
        $up_status = db('company_agent_user')->where("agent_id={$agent_id} and user_id={$user_id}")->update($add_exc);
        if ($up_status === false) {
            Db::rollback();
            Err::add('保存失败', RespCode::PARAMS_ERR);
            return false;
        }
        $user_info = db('company_user')->where("id={$user_id}")->find();
        if (!$user_info['itime_exclusive']) {
            //company_user更新专属客户时间
            $user_exc['itime_exclusive'] = $itime_exclusive;
            $user_exc['daytime_exclusive'] = $daytime_exclusive;
            $up_user = db('company_user')->where("id={$user_id}")->update($user_exc);
            if ($up_user === false) {
                Db::rollback();
                Err::add('保存失败', RespCode::PARAMS_ERR);
                return false;
            }
        }
        Db::commit();
        //存入门店专属客户数据
        $redisModel = Redis::getInstance();
        date_default_timezone_set('PRC');
        $today = date('Y-m-d', time());
        $shopid = db('company_agent')->where("id={$agent_id}")->value('company_shop_id');//门店id
        $is_add_exc = db('company_agent_user')->where("user_id={$user_id} and agent_id!={$agent_id} and company_shop_id={$shopid} and status=2")->find();
        if (!$is_add_exc) {
            //当前用户未与当前门店下经纪人(除开当前经纪人)绑定专属客户关系
            $potential = $redisModel->hget("companyshopstatistics_exclusive_{$today}", "{$shopid}");//查询已存入数据
            if ($potential) {
                $pull = json_decode($potential, true);
                array_push($pull, $user_id);//添加当前用户id
            } else {
                $pull[] = $user_id;//添加当前用户id
            }
            $redisModel->hset("companyshopstatistics_exclusive_{$today}", $shopid, json_encode($pull));//存入专属客户
        }
        return true;
    }

    /**
     * 获取帮填需求
     * @param $params
     */
    public function getHelpDemand($params)
    {
        $res1 = db('agent_user_demand')->alias('b')->where("user_id={$params['user_id']} and self_write=1")->find();
        $res2 = db('agent_user_demand')->alias('b')->where("user_id={$params['user_id']} and agent_id={$params['agent_id']} and self_write=0")->find();
        //定制需求：
        //自填时间   <  帮填时间  = 选帮填
        //自填时间   >=  帮填时间  = 选自填
        $demand_id = $res1['id'];
        if (isset($res2['utime']) && ($res2['utime'] > $res1['utime'])) {
            //帮填时间 大于 自填时间  = 选帮填数据
            $demand_id = $res2['id'];
        }
        $data = db("agent_user_demand")
            ->alias('ud')
            ->leftJoin('region r', 'r.city_code=ud.city_code')
            ->where('ud.id', $demand_id)
            ->field('r.name as city_name,ud.id,ud.type_id,ud.type,ud.price_section,ud.city_code,ud.area_code,ud.area_section,ud.door_section')
            ->select();
        if (empty($data)) {
            return [];
        } else {
            foreach ($data as &$v) {
                if ($v['type'] == self::TYPE1) {
                    $v['list_typename'] = '不限';
                    $v['info_business_or_community'] = '';
                }
                if ($v['type'] == self::TYPE2) {
                    $v_name = HouseVillage::get_Name($v['type_id']);
                    $v['list_typename'] = "只看'" . $v_name . "'小区";
                    $v['info_business_or_community'] = $v_name;
                }
                if ($v['type'] == self::TYPE3) {
                    $a_name = BusinessArea::get_Name($v['type_id']);
                    $v['list_typename'] = "只看'" . $a_name . "'商圈";
                    $v['info_business_or_community'] = $a_name;
                }
                $area_name = self::getArea($v['area_code'],$v['city_code']);//区域集合
                //列表展示市-区
                $v['list_title'] = self:: dealCityArea($area_name, $v['city_name']);
                $v['info_city_info'] = array('city_code' => $v['city_code'], 'name' => $v['city_name']);
                $v['info_area_info'] = $area_name;

                $v['info_type'] = $v['type'];
                $v['info_business_or_community_id'] = $v['type_id'];
                unset($v['type']);
                unset($v['city_name']);
                unset($v['city_code']);
                unset($v['area_code']);
                $v['info_price_section'] = $v['price_section'] ? explode(',', $v['price_section']) : [];
                $v['info_price_section_name'] = self::managerDemand($v['price_section'], 1);
                $v['info_area_section'] = $v['area_section'] ? explode(',', $v['area_section']) : [];
                $v['info_area_section_name'] = self::managerDemand($v['area_section'], 2);
                unset($v['price_section']);
                unset($v['area_section']);
                unset($v['type_id']);
                $v['info_door_section'] = $v['door_section'] ? explode(',', $v['door_section']) : [];
                $v['info_door_section_name'] = self::managerDemand($v['door_section'], 6);
                unset($v['door_section']);
            }
            return array_values($data);
        }

    }


    /**
     * 增加帮填需求互动记录
     * @param int $agent_user_id
     * @param int $house_id
     * @return int|string
     */
    public function addInterLog($agent_user_id = 0)
    {
        $add_inter_log['agent_user_id'] = $agent_user_id;
        $add_inter_log['type'] = 12;
        $add_inter_log['house_id'] = 0;
        $add_inter_log['trends_id'] = 0;
        $add_inter_log['itime'] = time();
        $add_inter_id = db('agent_user_interaction_log')->insertGetId($add_inter_log);
        return $add_inter_id ?? 0;
    }


    /**
     * 根据id获取小区所在区域的code
     * @param int $id
     * @return mixed|string
     */
    public static function getVillageCity($id=0){
        $re=db('house_village')->where("id={$id}")->value('city_code');
        return $re??'';
    }

    /**
     *  根据id获取商圈所在区域的code
     * @param int $id
     * @return mixed
     */
    public static function getBusinessCity($id=0){
        $re=db('business_area')->where("id={$id}")->value('city_id');
        return $re??'';
    }

    public function getDemandHouse($params,$pageSize){

        $agent_demand = Db::name("agent_demand")->where('agent_id', $params['agent_id'])->where('id',$params['id'])->find();
        if (!$agent_demand){
            return [];
        }
        $houseModel=new House();
        $column = array_merge($houseModel->houseFields, $houseModel->villageFields, $houseModel->typeFields, $houseModel->auctionFields,$houseModel->businessFields,$houseModel->reginFields);
        $map = [];
        $map[] = ['h.is_shelf', '=', 1];
        $map[] = ['h.deleted', '=', 0];
        $map[] = ['ha.auction_status', 'in', [1, 2]];
        //区域
        if ($agent_demand['type'] == 1) {//不限
            if ($agent_demand['area_code']){
                $map[] = ['h.city_code', 'in', $agent_demand['area_code']];
            }else{
                //需求不限区域
                $region_data = Db::name('region')->where('city_code', $agent_demand['city_code'])->find();
                $codes = $region_data['p_codes'] . $agent_demand['city_code'] . ',';
                $map[] = ['h.city_codes', 'like', trim($codes) . '%'];
            }

        }
        if ($agent_demand['type'] == 2) {//小区
            $map[] = ['h.village_id', '=', $agent_demand['type_id']];
        }
        if ($agent_demand['type'] == 3) {//商圈
            $map[] = ['h.business_area_id', '=', $agent_demand['type_id']];
        }

        //价格区间
        $map[] = createSectionQuery1($agent_demand['price_section'], 'ha.initial_price');


        //面积区间
        $map[] = createSectionQuery1($agent_demand['area_section'], 'h.build_area');

        //户型
        if ($agent_demand['door_section']){
            $map[] = createSectionQuery1($agent_demand['door_section'], 'h.bedroom');
        }

        $orderby = ['ha.auction_status' => 'asc', 'ha.start_time' => 'desc'];
        $whereRaw='';
        if (!empty($params['discount'])){
            //折扣
            $whereRaw.=createSectionDiscount($params['discount'], 'ha.discount');
        }
        $map=$this->getDemandScreening($params,$map);
        $orderby=$this->getDemandOrder($params,$orderby);
        $res = $houseModel->house_list($map, $whereRaw, $column, $params['page'], $pageSize, $orderby, '');
        $reData = $houseModel->house_list_style($res[0]);
        $list['count'] =$res[1];//数据总条数
        $list['page'] = (int)$res[2];//当前页码
        $list['pageSize'] = $pageSize;//每页显示条数
        $list['pageNum'] = $res[3];//每页显示条数
        $list['list'] = $reData;
        return $list;

    }

    public function getDemandWhere($params){
        $agent_demand = Db::name("agent_demand")->where('agent_id', $params['agent_id'])->where('id',$params['id'])->find();
        if(!$agent_demand){
            return [];
        }
        $city_code = $agent_demand['city_code'];
        $discount_interval = IntervalConfig::all_intervel($city_code)['discount_interval'];//折扣区间
        $p_setion=explode(',',$agent_demand['price_section']);
        $price_interval=$this->dealDemandConfig($p_setion,1);
        $b_setion=explode(',',$agent_demand['area_section']);
        $build_area_interval=$this->dealDemandConfig($b_setion,2);
        $d_setion=explode(',',$agent_demand['door_section']);
        $bedroom=$this->dealDemandConfig($d_setion,6);
        $a_status=array(
            ['id' => 1, 'name' => '待开始'],
            ['id' => 2, 'name' => '进行中']
        );
        $a_type = IntervalConfig::$a_type; //拍卖阶段
        $orderby = IntervalConfig::$orderby;//排序
        if ($agent_demand['area_code']){
            $Region=$this->getDemandBusiness($agent_demand['area_code'],$agent_demand['id'],$agent_demand);
        }else{
            $Region = Region::get_list($agent_demand['city_code']);//区域，商圈
        }

        $data['discount_interval']=$discount_interval;//价格
        $data['price_interval']=$price_interval;//价格
        $data['build_area_interval']=$build_area_interval;//面积
        $data['bedroom']=$bedroom;//户型
        $data['a_status']=$a_status;//拍卖类型
        $data['a_type']=$a_type;//拍卖阶段
        $data['orderby']=$orderby;//拍卖阶段
        $data['Region']=$Region;//拍卖阶段
        return $data;

    }

    public function dealDemandConfig($data,$type){
        foreach ($data as $key =>$value){
            $ps=explode('-',$value);
            $p_name=IntervalConfig::getConfig_name($ps[0], $ps[1], $type);
            if ($type==6){
                $arr[$ps[0]]=['name'=>$p_name,'id'=>$ps[0]];
            }else{
                $arr[$ps[0]]=['name'=>$p_name,'key'=>$value];
            }
        }
        ksort($arr);
        $arr=array_values($arr);
        return $arr??[];
    }

    /**
     * 定制需求 区域，商圈
     * @param int $area_code
     * @param int $demand_id
     * @return array|false|PDOStatement|string|Collection
     */
    public function getDemandBusiness($area_code=0,$demand_id=0,$demand=[]){
        $column = ['name', 'city_code', 'id'];
        //区域
        $per = db::name('region')->where("city_code in ({$area_code})")->order('weights asc')->field($column)->select();
        $ids = array_column($per, 'city_code');
        //区域下面所有商圈
        if ($demand['type']==self::TYPE3){
            //只看商圈
            $business_area = db::name('business_area')->where('id', $demand['type_id'])->field('name,city_id,id')->select();
        }else{
            $business_area = db::name('business_area')->where('city_id', 'in', $ids)->field('name,city_id,id')->select();

        }
        $per = array_column($per, null, 'city_code');

        foreach ($business_area as $val) {
            if (isset($per[$val['city_id']])) {
                $per[$val['city_id']]['children'][] = $val;
            }
        }
        $per = array_values($per);
        for ($i2 = 0; $i2 < count($per); $i2++) {
            $str = 'c-' . $per[$i2]['city_code'];
            if (!empty($per[$i2]['children'])) {
                array_unshift($per[$i2]['children'], ['name' => '不限', 'city_id' => $per[$i2]['city_code'], 'id' => $str]);
            } else {
                $per[$i2]['children'] = [['name' => '不限', "city_id" => $per[$i2]['id'], "id" => $str]];
            }
        }
        array_unshift($per, [
            'name' => '不限',
            'city_code' => $demand_id.'_all',
            'id' => 0,
            'children' => [['name' => '不限', "city_id" => $demand_id.'_all', "id" => 0]]
        ]);
        return $per;
    }

    /**
     * 智能选房->列表筛选
     * @param $params
     * @param array $map
     * @return array
     */
    public function getDemandScreening($params,$map=[]){
        //商圈
        if (!empty($params['area_id'])) {
            $area_id = explode(',', $params['area_id']);
            if (isset($area_id[1])) {
                $map[] = ['h.business_area_id', 'in', $area_id];
            } else {
                if (substr($area_id[0], 0, 1) == 'c') {
                    $map[] = ['h.city_code', '=', substr($area_id[0], 2)];
                } else {
                    $map[] = ['h.business_area_id', '=', $area_id[0]];
                }
            }
        }
        //价格区间
        if (!empty($params['initial_price'])) {
            $map[] = createSectionQuery1($params['initial_price'], 'ha.initial_price');
        }
        //面积区间
        if (!empty($params['build_area'])) {
            $map[] = createSectionQuery1($params['build_area'], 'h.build_area');
        }
        //拍卖状态
        if (!empty($params['auction_status'])) {
            $auction_status = explode(',', $params['auction_status']);
            $map[] = ['ha.auction_status', 'in', $auction_status];
        }
        //折扣比
//        if (!empty($params['discount'])) {
//            $map[] = createSectionQuery1($params['discount'], 'ha.discount');
//        }

        //拍卖阶段
        if (!empty($params['au_type'])) {
            $au_type = explode(',', $params['au_type']);
            $map[] = ['ha.type', 'in', $au_type];
        }
        //户型
        if (!empty($params['bedroom'])) {
            $bedroom = explode(',', $params['bedroom']);
            if(isset($bedroom[1])){
                if(in_array(5,$bedroom)){
                    $bedmap[0] = 'h.bedroom';
                    $bedmap[1][] = ['>=', 5];
                    $bedmap[1][] = ['in', $bedroom];
                    $bedmap[2] = 'or';
                }else{
                    $bedmap[] = ['h.bedroom', 'in', $bedroom];
                }
                $map[] = $bedmap;
            }else{
                if ($params['bedroom'] < 5) {
                    $map[] = ['h.bedroom', 'in', $bedroom];
                } else {
                    $map[] = ['h.bedroom', '>=', $params['bedroom']];
                }
            }
        }

        return $map;
    }


    /**
     * 定制需求 排序
     * @param $params
     * @param array $orderby
     * @return array
     */
    public function getDemandOrder($params,$orderby=[]){
        //排序
        if (!empty($params['orderby'])) {
            //默认
            if ($params['orderby'] == IntervalConfig::ORDERBBY1) {
                $orderby = ['ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.initial_price'=>'asc','ha.discount' => 'asc'];
            }
            //按价格从高到低
            if ($params['orderby'] == IntervalConfig::ORDERBBY2) {
                $orderby = ['ha.initial_price'=>'desc','ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.discount' => 'asc'];
            }
            //按价格从低到高
            if ($params['orderby'] == IntervalConfig::ORDERBBY3) {
                $orderby = ['ha.initial_price'=>'asc','ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.discount' => 'asc'];
            }
            //按折扣从高到低
            if ($params['orderby'] == IntervalConfig::ORDERBBY4) {
                $orderby = ['ha.discount' => 'desc','ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.initial_price'=>'asc'];

            }
            //按折扣从低到高
            if ($params['orderby'] == IntervalConfig::ORDERBBY5) {
                $orderby = ['ha.discount' => 'asc','ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.initial_price'=>'asc'];
            }
            //开拍时间由远及近
            if ($params['orderby'] == IntervalConfig::ORDERBBY6) {
                $orderby = ['ha.start_time' => 'desc', 'ha.auction_status' => 'asc'];
            }
            //开拍时间由近及远
            if ($params['orderby'] == IntervalConfig::ORDERBBY7) {
                $orderby = ['ha.start_time' => 'asc','ha.auction_status' => 'asc', 'ha.initial_price'=>'asc','ha.discount' => 'asc'];
            }
            //最近发布
            if ($params['orderby'] == IntervalConfig::ORDERBBY8) {
                $orderby = ['ha.utime' => 'desc','ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.initial_price'=>'asc','ha.discount' => 'asc'];
            }
        } else {
            $orderby = ['ha.auction_status' => 'asc', 'ha.start_time' => 'asc','ha.initial_price'=>'asc','ha.discount' => 'asc'];
        }
        return $orderby;
    }

    /**
     * 比较定制需求是否有数据改变
     * @param array $old_data
     * @param array $new_data
     * @return bool
     */
    public function checkDataUp($old_data=[],$new_data=[]){
        unset($old_data['id']);
        unset($old_data['itime']);
        unset($old_data['utime']);
        unset($new_data['itime']);
        unset($new_data['utime']);
        array_values($old_data);
        array_values($new_data);
        $diff= array_diff($old_data,$new_data);
        if ($diff){
            return true;
        }else{
            return false;
        }

    }

}
